package MyDaily.Servlet;

/*处理登录操作的servlet*/
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import MyDaily.dao.user.Login_Query;
import MyDaily.pojo.User;

/**
 * Servlet implementation class LogionServlet
 */
@WebServlet("/LogionServlet")
public class LogionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LogionServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置请求和响应数据的字符集编码
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		// 获取页面用户输入的用户名,密码和是否勾选了记住密码
		String name = request.getParameter("username");
		String password = request.getParameter("userpassword");
		String strCookie = request.getParameter("Cookie");
		// 调用查询方法
		List<User> uList = Login_Query.LoginQuery(name, password);
		//创建session
		HttpSession session = request.getSession();
		// 用户输入和查询数据进行比较
		// 判断用户输入和查询比较
		if (uList.size() > 0) {
			if (strCookie != null) {// 用户选择记住密码功能
				Cookie ckna = new Cookie("name", name);
				ckna.setMaxAge(60 * 60 * 24 * 30);
				Cookie ckpwd = new Cookie("password", password);
				ckpwd.setMaxAge(60 * 60 * 24 * 30);// cookie有效期30天
				response.addCookie(ckna);// 将用户name发送给客服端
				response.addCookie(ckpwd);
				// 回首页
				//将name放在session中，在首页调用
				session.setAttribute("name", name);
				request.getRequestDispatcher("home.jsp").forward(request, response);
			} else {
				// 未勾选记住
				// 转发至首页界面
				//将name放在session中，在首页调用
				session.setAttribute("name", name);
				request.getRequestDispatcher("home.jsp").forward(request, response);
			}
		} else {
			request.setAttribute("msg", "对不起，账号或密码不正确");
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
	}

}
